package logic

import (
	"context"
	"doctor-medicine-system/medrpc/internal/svc"
	"doctor-medicine-system/medrpc/medrpc"
	"doctor-medicine-system/models/mysql"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type MedAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMedAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MedAddLogic {
	return &MedAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *MedAddLogic) MedAdd(in *medrpc.MedAddRequest) (*medrpc.MedAddResponse, error) {
	// todo: add your logic here and delete this line

	var med mysql.Med

	err := med.FindMedByName(mysql.DB, in.MedName)
	if err != nil {
		return nil, errors.New("查询失败")
	}

	if med.ID != 0 {
		return nil, errors.New("该药品已存在")
	}

	med = mysql.Med{
		MedName: in.MedName,
		MedSize: in.MedSize,
		MedFrom: in.MedFrom,
	}

	err = med.MedAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("添加失败")
	}

	return &medrpc.MedAddResponse{
		MedId: int64(med.ID),
	}, nil
}
